<?php
namespace app\home\controller;
use think\facade\Request;
use think\Db;
use think\Controller;
/**
 * @title 登录注册
 * @description 接口说明
 * @group 西红柿
 */
class Login extends Controller
{
	/**
     * @title 注册
     * @author 雪飞鸟
     * @url /home/Login/register
     * @method POST
     * @param name:userPhone type:int require:1 default:1 other: desc:手机号
     * @param name:password type:string require:1 default:1 other: desc:登录密码
     * @param name:phoneCode type:int require:1 default:1 other: desc:手机验证码
     * @param name:rpass type:string require:1 default:1 other: desc:手机验证码
     */
    public function register() 
    {
        if (Request::isPost()) 
        {
            $data = Request::post();
            
            if (!$data['userPhone'] || !$data['phoneCode'] || !$data['password'] || !$data['rPass']) 
            {
                # 检测参数完整
                return json_error('请填写全部内容');
            }
            if(!preg_match('/(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,16}$/',$data['password']))
            {
                # 6~16位字母、数字、符号
                return json_error(['code'=>400,'msg'=>'请输入6-16位字母数字符号至少两种组合的密码']);
            }

            // 判断两次密码
            if ($data['password'] != $data['rPass']) 
            {
                return json_error('两次密码不一致');
            }

            if (!preg_match("/^1[345789]\d{9}$/", $data['userPhone'])) 
            {
                # 验证手机号
                return json_error('请填写有效手机号');
            }

            // 检测手机号是否存在
            $arr = db('User')->where(['user_phone' => $data['userPhone']])->find();
            if(is_array($arr))
            {
                return json_error('该手机号已注册，请登录');
            }

            //验证码是否失效
            $phone_code = db('phone_code')->where(['user_phone' => $data['userPhone']])->order('mes_id desc')->find();
            $smsnum_arr = explode(',', $phone_code['phone_code']);
            if (time() - $smsnum_arr[1] >= 3600*24) 
            {
                return json_error('验证码已失效');
            }
            //验证吗是否正确
            if ($data['phoneCode'] . 'zc' != $smsnum_arr[0] || $data['userPhone'] != $phone_code['user_phone']) 
            {
                return json_error('手机号或验证码错误！');
            }
            
            if (array_key_exists('code', $data)) 
            {
                # 如果有推荐码
                $code   = $data['code'];
                $rInfo  = db('user')->where(['user_reg_code' =>  $code])->find();
                if ($rInfo) 
                {
                    $pid = $rInfo['user_id'];
                }
                else
                {
                    return json_error('推荐人不存在');
                }
            }
            else
            {
                $pid = 0;
            }
            // 生成邀请码
            $code_num   = code_num();
            // 组装数据
            $arr['user_phone']     = trim($data['userPhone']);
            $arr['user_password']  = md5(trim($data['password']));
            $arr['user_reg_code']  = $code_num;
            $arr['create_time']    = date("Y-m-d H:i:s");
            $arr['user_parent']    = $pid;
            $arr['user_headimg']   = '/Public/Home/img/portait-man.png';
            $uN = db('user')->insertGetId($arr);
            if ($uN) 
            {
                # 注册成功
                return json_success('注册成功');
            }
            else
            {
                return json_error('注册失败');
            }

        } 
        else 
        {
            $code = Request::get('code');
            $code? '': $code=123456;
            $this->assign('code', $code);
            return $this->fetch('registerEwm'); 
        }
    }

	 /**
     * @title 处理登录
     * @author 雪飞鸟
     * @url /home/Login/doLogin
     * @method POST
     * @param name:phone type:int require:1 default:1 other: desc:手机号
     * @param name:password type:int require:1 default:1 other: desc:密码
     * @return token:912b810c47c710019ac3ce35652407aeed
     */
    public function doLogin()
    {
        if (Request::isPost()) 
        {
            $username   = trim(Request::post('phone'));
            $password   = trim(Request::post('password'));
            if (empty($username) || empty($password)) 
            {
                return json_error('请先完善登录信息!');
                die();
            }

            $user = db('user')->where(array('user_phone|user_name' => $username))->find();
            if (!$user) 
            {
                return json_error('用户名不存在!');
            } 
            if (md5($password) != $user['user_password']) 
            {
                return json_error('密码错误');
            }
            // 生成token
            $tokenN = $this->generateToken($user['user_id']);
            if ($tokenN) 
            {
                # token写入成功
                if (!$user['user_status']) 
                {
                    # 第一次登陆奖励6.5金币
                    $reward = db('user')->where(['user_id' => $user['user_id']])->update(['user_gold' => 6.5, 'user_status' => 1]);
                    if (!$reward) 
                    {
                        # 奖励金币失败
                        return json_error('登陆失败');
                    }
                }
                $uInfo = db('user')->where(array('user_phone|user_name' => $username))->find();
                return json_success(['token' => $uInfo['user_token']], '登录成功');
            }


        } 
        else 
        {
            return json_success('非法请求');
        }
    }

    /**
     * @title 获取注册验证码
     * @author 雪飞鸟
     * @url /home/Login/getPhoneCode
     * @method POST
     * @param name:phone type:int require:1 default:1 other: desc:手机号
     * @return code:991606 
     */
    public function getPhoneCode()
    {
        $phone = trim(Request::post('phone'));
        return yzm($phone);
    }

    /**
     * @title 生成token
     * @author 雪飞鸟
     * @url /home/Login/generateToken
     * @method POST
     * @param name:uId type:int require:1 default:无 other:无 desc:用户id
     * @return updateN:更新条数 
     */
    public function generateToken($uId)
    {
        $token = $uId.md5(mt_rand(1000000,9999999).time());
        $n = db('user')->where(['user_token' => $token])->find();
        if ($n) 
        {
            # 如果存在
            $this->generateToken();
        }
        else
        {
            $tokenN = db('user')->where(['user_id' => $uId])->update(['user_token' => $token]);
            return $tokenN;
        }
    }

}